import { action, observable, toJS } from "mobx";
import EXCELAPI from '../../apis/exceldata';
import { uniqBy } from 'lodash';
import API from '../../apis/data';
import HeaderCellType from './HeaderCellType';
import PicCellType from './PicCellType'
import BaseCellType from './BaseCellType'
import { message, Modal } from 'antd';
import { fillinTypes } from "../../constants/app";
import { WeaLocaleProvider } from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;
//import FieldCellType, { FieldTypeName } from "../excel/celltypes/FieldCellType";

export default class DataExcelStore {

    @observable designStore;
    @observable dataSource = [];
    @observable workbook;
    @observable visible = false;
    @observable previewImage;
    @observable sort;
    @observable page;
    @observable pageSize = 50;
    @observable sortKey;
    @observable options = [];
    @observable selectValue = "";
    @observable filterVisible = false;
    @observable selectTop;
    @observable selectLeft;
    @observable columnOption = {};
    @observable data;
    @observable sortType = "";
    oldInfo = "";

    @observable filterOptions = [];
    @observable filterLeft = 0;
    @observable filterTop = 0;
    @observable filterWidth = 0;
    @observable filterLoading = false;
    @observable filterValue = [];
    @observable filterCheckedValue = {};
    @observable filterQueryedDatas = {};
    @observable sessionKey;
    @observable quickSearchValue;
    @observable filterOptions;
    @observable filterKey;
    @observable indeterminate;
    @observable checkAll;
    @observable otherpara;
    @observable dbType;
    @observable lockColumn = 0;
    @observable row;
    @observable col;
    @observable isColseView = true;
    @observable colAlign = -1;
    @observable columnList = [];
    @observable columnsAlign = {};
    @observable columnsWith = {};
    @observable columnsSearch = {};
    @observable clientWidth;
    @observable colLock;
    @observable isSearch;
    @observable colPropList;
    @observable downloadCondition = {};
    @observable isdownload = "0";
    @observable fieldgroup = "";

    constructor(designStore) {
        this.designStore = designStore;
    }

    @action
    initWorkbook = (workbook) => {
        window.workbookInstance = this.workbook = workbook;
        this.workbook.bind(GC.Spread.Sheets.Events.TopRowChanged, this.topRowChanged);
        this.workbook.bind(GC.Spread.Sheets.Events.LeftColumnChanged, this.LeftColumnChanged)
        this.workbook.getHost().addEventListener('click', this.clickAnyWhere);
        this.workbook.bind(GC.Spread.Sheets.Events.EnterCell, this.enterCell);
        this.workbook.bind(GC.Spread.Sheets.Events.SelectionChanged, this.selectionChanged);
        this.workbook.bind(GC.Spread.Sheets.Events.ColumnWidthChanged, this.columnWidthChanged);

        this.dataSource = new GC.Spread.Sheets.Bindings.CellBindingSource({ datas: [] });
        this.workbook.options.tabStripVisible = false; // 左下角tab页不显示
    }
    enterCell = (e, info) => {
        const { sheet, row, col } = info;
        const isTable = !!sheet.tables.find(row, col);
        if (isTable && this.otherpara) {
            this.workbook.contextMenu.menuData = [{
                name: "edc.data.list.showData",
                text: '查看数据',
                workArea: "viewporttable",
                command: this.showData
            }];
        } else {
            this.workbook.contextMenu.menuData = [];
        }
    }
    showData = () => {
        const col = this.workbook.getActiveSheet().getActiveColumnIndex();
        const row = this.workbook.getActiveSheet().getActiveRowIndex();
        this.isColseView = false;
        if (this.colseView) {
            clearTimeout(this.colseView);
        }
        this.col = col;
        this.row = row;
        const { row: startRow } = this.table.dataRange();
        const dataIndex = row - startRow;
        const datas = this.dataSource.getValue('datas');

        const rowData = datas[dataIndex];


        if (this.designStore.fillinType === fillinTypes.MULTI) {
            //store.showExcel(operate.otherpara,record.randomFieldId);
            this.designStore.slideStore.init(this.params = {
                pageid: this.otherpara,
                userdataid: rowData.randomFieldId,
                formid: this.designStore.selectedForm,
            });
        } else {
            this.designStore.fetchDetailData(rowData.randomFieldId, this.otherpara);
        }


        this.designStore.changeHide(true);
        this.designStore.conditionVisible = false;
        this.designStore.showSearchAd = false;
        this.designStore.showContent(false);
    }



    @action
    bindExcelSource = (datas) => {
        if (this.workbook) {
            if (this.page === 2) {
                this.hasMore = true;
                if (this.dataSource) {
                    this.dataSource.setValue('datas', []);
                }

                if (datas.ops && datas.ops.length > 0) {
                    this.otherpara = datas.ops[0]["otherpara"] || "";
                    this.dbType = datas.ops[0]["href"] || "";
                }

                Promise.all([this.pushColumns(datas.columns), this.pushDatas(datas.datas)]).then(this.bingDatas);
            }
            Promise.all([this.pushDatas(datas.datas)]).then(this.bingDatas);
            // const sheet = this.workbook.getActiveSheet();

            // sheet.autoGenerateColumns = true;
            // this.datas = datas.datas.map(d => {
            //     if (d) {
            //         for (let k in d) {
            //             if (k.indexOf("span") == -1 || k == 'randomFieldIdspan') {
            //                 delete d[k];
            //             }
            //         }
            //     }
            //     return d;
            // })

            //let maxColumn = 0;
            // datas.columns.filter(s => (s.dbField && s.dbField != 'randomFieldId')).forEach((r, index) => {
            //     //sheet.bindColumn(index, { name: r.dbField + 'span', displayName: r.title })
            //     this.columns[r.dbField + 'span'] = r.title;
            //     maxColumn ++;
            // });

            //this.datas.unshift(this.columns);
            // this.pushColumns( datas.columns);
            // this.pushDatas(datas.datas);
            //sheet.setDataSource(this.datas);


            // 自适应宽高
            // for (let i = 0; i < maxColumn; i++) {

            //     sheet.autoFitColumn(i);
            // }


        } else {
            setTimeout(() => {
                this.bindExcelSource(datas);
            }, 50);
        }

    }

    // @action setColumns = (result) => {
    //     return new Promise(resolve => {
    //         if (result.status === '1') {
    //             this.siderWidth = result.siderWidth;
    //             this.pushColumns(result.resultList);
    //         }
    //         resolve();
    //     });
    // }


    @action getColumnsStyle = (columns) => {
        API.getExcelStyle({
            formid: this.designStore.selectedForm,
            appid: this.designStore.appid,
        });
    }

    @action pushColumns = (columns) => {
        this.backColumn = columns.map(d => {
            return {
                ...d,
                // length: getTextLength(d),
                // qfws: getFloatQfws(d)
            }
        });
        columns = columns.filter(d => d.dataIndex !== 'randomFieldId' && d.title);
        this.workbook.suspendPaint();
        this.workbook.fromJSON({}, false);
        const sheet = this.workbook.getSheet(0);
        (sheet).setChangedValue = this.setChangedValue;
        sheet.setColumnCount(columns.length);
        window.table = this.table = sheet.tables.add('表格', 0, 0, 1, columns.length,
            GC.Spread.Sheets.Tables.TableThemes.light11, { showHeader: false, rowFilterVisible: false });
        sheet.modifyedValues = {};
        //sheet.frozenRowCount(1);
        //sheet.frozenColumnCount(columns.length);

        const style = GC.Spread.Sheets.Tables.TableThemes.light11.headerRowStyle();
        let widths = [];
        let aligns = [];
        let totalWidth = 0;
        this.clientWidth = document.documentElement.clientWidth - sheet.getColumnWidth(0, GC.Spread.Sheets.SheetArea.rowHeader);
        //const perWidth = clientWidth / 100;
        //.filter(s => (s.dbField && s.dbField != 'randomFieldId'))
        this.c = [];
        this.colPropList = {};
        this.columnList = [];
        this.designStore.hasFields = '0';
        this.designStore.fieldOptions = [];
        this.columns = columns.map((d, index) => {
            this.columnList.push(d.dbField);
            this.colPropList[d.orderkey] = d;
            let width = this.columnsWith[d.dbField];
            if (!width) {
                width = 'default'
            }
            // 是否有文件类型的字段
            if (d.transMethodOther && d.transMethodOther.startsWith('6+')) {
                this.designStore.hasFields = '1';
            }
            this.designStore.fieldOptions.push({ key: d.dbField, showname: d.title });
            // let width = parseFloat(d.colwidth);
            // if (d.width !== void 0) {
            //     width = d.width / perWidth;
            // }
            // totalWidth += width;
            widths.push(width);
            let align = this.columnsAlign[d.dbField];
            if (!align) {
                align = 'default'
            }
            aligns.push(align);
            sheet.getCell(0, index, GC.Spread.Sheets.SheetArea.colHeader)
                .font(style.font)
                .foreColor(style.foreColor)
                .backColor(style.backColor)
                .cellType(HeaderCellType(d, this));
            // sheet.setCellType(0, index, HeaderCellType(d, this));
            return new GC.Spread.Sheets.Tables.TableColumn(d.id).dataField(d.dbField + 'span').name(d.title);
        });
        // const noneWidths = widths.filter(d => d <= 0);
        // let avgwidth = 5;
        // if (totalWidth + noneWidths.length * 5 < 100) {
        //     avgwidth = (100 - totalWidth) / noneWidths.length;
        // }

        // avgwidth = avgwidth * perWidth;

        const realWidth = this.clientWidth / widths.length;


        widths.forEach((width, index) => {
            //sheet.setColumnWidth(index, width <= 0 ? avgwidth : width * perWidth);
            if (width == 'default' || width <= 0) {
                sheet.setColumnWidth(index, Math.max(this.clientWidth * (0.05), realWidth));
            } else {

                sheet.setColumnWidth(index, width);
            }

        })

        aligns.forEach((align, index) => {
            if (align != 'default' && align >= 0) {
                sheet.getRange(-1, index).hAlign(align);
            }
        })

        this.table.bindingPath('datas');
        this.table.bindColumns(this.columns);
        this.table.autoGenerateColumns(false);
        // sheet.bindColumns(this.columns);
        if (this.lockColumn > 0) {
            this.workbook.getActiveSheet().frozenColumnCount(this.lockColumn);
        }
        this.workbook.resumePaint();
    }

    @action
    getExcelData = () => {

        this.loading = true;
        if (this.page == 1) {
            Promise.all([EXCELAPI.datas({
                dataKey: this.sessionKey,
                current: this.page++,
                pageSize: this.pageSize,
                sortParams: this.sort
            }), API.getExcelStyle({
                formid: this.designStore.selectedForm,
                appid: this.designStore.appid,
            })]).then(([datas, styles]) => {
                if (styles) {
                    this.columnsSearch = styles.columnsSearch ? JSON.parse(styles.columnsSearch || {}) : {};
                    this.columnsAlign = styles.columnsAlign ? JSON.parse(styles.columnsAlign || {}) : {};
                    this.columnsWith = styles.columnsWith ? JSON.parse(styles.columnsWith || {}) : {};
                    this.downloadCondition = styles.downloadCondition ? JSON.parse(styles.downloadCondition || {}) : {};
                } else {
                    this.columnsSearch = {};
                    this.columnsAlign = {};
                    this.columnsWith = {};
                    this.downloadCondition = {};
                }
                this.bindExcelSource(datas);
            })
        } else {
            EXCELAPI.datas({
                dataKey: this.sessionKey,
                current: this.page++,
                pageSize: this.pageSize,
                sortParams: this.sort
            }).then(this.bindExcelSource)
        }

    }

    @action
    initExcelData = () => {
        // this.designStore.changeHide(false);
        this.filterValue = [];
        this.filterCheckedValue = {};
        this.filterQueryedDatas = {};
        this.filterVisible = false;
        this.indeterminate = false;
        this.checkAll = false;
        this.sortKey = "";
        this.sort = "";
        this.lockColumn = 0;
        this.columnsAlign = {};
        this.columnsWith = {};
        this.columnsSearch = {};
        this.downloadCondition = {};
        this.designStore.changeHide(false);
        this.designStore.showContent(false);
    }
    @action
    getExcelDataBySort = (sort) => {
        this.sort = JSON.stringify(sort);
        this.page = 1;
        this.getExcelData();
    }


    // if("mysql".equals(dbType)) {
    //     prefix = "";
    //     suffix = "";
    // } else if("oracle".equals(dbType)){
    //     prefix = " to_char(";
    //     suffix = ") ";
    // } else {
    //     prefix = " cast(";
    //     suffix = " as varchar(max)) ";
    // }
    @action
    changeSort = (sort) => {
        const s = this.filterKey + '@' + sort;
        this.filterVisible = false;
        if (s == this.sortKey) {
            return;
        } else {
            this.sortKey = s;
            this.sortType = sort;
        }

        let key = this.filterKey;

        // if(this.dbType) {
        //     if(this.dbType == 'mysql') {

        //     } else if(this.dbType == 'sqlserver') {
        //         key = " cast(" + key + " as varchar(max))";
        //     } else {
        //         key = " to_char(" + key + ")";
        //     }
        // }

        this.getExcelDataBySort(this.filterKey == 't1.createDate' ?
            [{ "orderkey": this.filterKey, "sortOrder": sort }, { "orderkey": "t1.createTime", "sortOrder": sort }]
            : [{ "orderkey": key, "sortOrder": sort }]);
    }

    // 点击抬头
    @action
    cilckSort = (orderkey) => {

        this.filterVisible = false;
        let sort = 'ascend';
        if (this.sortKey) {

            const sorts = this.sortKey.split("@");
            if (sorts[0] == orderkey) {
                sort = sorts[1] == 'ascend' ? 'descend' : 'ascend'
            }
        }
        this.sortKey = orderkey + "@" + sort;

        // if(this.dbType) {
        //     if(this.dbType == 'mysql') {

        //     } else if(this.dbType == 'sqlserver') {
        //         key = " cast(" + key + " as varchar(max))";
        //     } else {
        //         key = " to_char(" + key + ")";
        //     }
        // }

        this.getExcelDataBySort(orderkey == 't1.createDate' ?
            [{ "orderkey": orderkey, "sortOrder": sort }, { "orderkey": "t1.createTime", "sortOrder": sort }]
            : [{ "orderkey": orderkey, "sortOrder": sort }]);
    }


    clickAnyWhere = (e) => {
        // this.filterVisible = false;
        //this.showData();

        if (this.isColseView) {
            this.colseView = setTimeout(() => {
                this.designStore.changeHide(false);
            }, 50);
        } else {
            this.isColseView = true;
        }

    }

    selectionChanged = () => {
        const activeCol = this.workbook.getActiveSheet().getActiveColumnIndex();

        this.colAlign = this.workbook.getActiveSheet().getCell(0, activeCol).hAlign();
        const colIndex = activeCol + 1;
        if (colIndex == this.lockColumn) {
            this.colLock = 1;
        } else {
            this.colLock = 0;
        }
    }

    mouseOverAnyWhere = (e) => {
        return;
    }


    @action pushDatas = (datas) => {
        if (datas.length < this.pageSize) {
            this.hasMore = false;
        }
        const olddatas = this.dataSource.getValue('datas');
        const newdatas = uniqBy([...olddatas, ...datas], d => `${d.randomFieldId}-${d.randomFieldSubKeyid || ''}`);
        this.dataSource.setValue('datas', newdatas);
        this.loading = false;
    }

    @action bingDatas = () => {
        this.workbook.suspendPaint();
        this.workbook.sheets.forEach(sheet => {
            sheet.setDataSource(this.dataSource);
        });
        const sheet = this.workbook.getActiveSheet();
        this.table.bindingPath('datas');
        const { row, rowCount, colCount } = this.table.dataRange();
        this.backColumn.filter(d => d.title).forEach((col, index) => {
            let cellType;
            let htmlType = 1;
            if (col.transMethodOther) {
                htmlType = col.transMethodOther.split('+')[0];
            }

            if (htmlType == 6) {
                for (let r = 0; r < rowCount; r++) {
                    cellType = PicCellType(this.dataSource.getValue('datas')[r][col.dbField + "span"], this);
                    sheet.getRange(row + r, index, 1, 1).cellType(cellType);
                }
            } else if (col.dbField == 'creator') {
                for (let r = 0; r < rowCount; r++) {
                    const value = this.dataSource.getValue('datas')[r][col.dbField + "span"];
                    if (value.indexOf("|weixin|") > 0) {
                        cellType = PicCellType(value, this);
                        sheet.getRange(row + r, index, 1, 1).cellType(cellType);
                    } else {
                        cellType = BaseCellType(col, false, this);
                        sheet.getRange(row + r, index, 1, 1).cellType(cellType);
                    }

                }
            } else {
                cellType = BaseCellType(col, false, this);
                sheet.getRange(row, index, rowCount, 1).cellType(cellType);
            }


        });
        sheet.getRange(0, 0, rowCount, colCount).formatter("@").vAlign(GC.Spread.Sheets.VerticalAlign.center);
        sheet.setRowCount(rowCount);

        this.workbook.options.tabStripVisible = false; // 左下角tab页不显示
        this.workbook.resumePaint();
        this.enterCell('', { sheet, row: sheet.getActiveRowIndex(), col: sheet.getActiveColumnIndex() })
    }

    @action topRowChanged = (e, info) => {
        const { newTopRow, oldTopRow } = info;
        if (this.table && newTopRow > oldTopRow) {
            const { row, rowCount } = this.table.range();
            if (newTopRow >= row + rowCount - this.pageSize / 2) {
                if (this.hasMore) {
                    if (!this.loading) {
                        this.loading = true;
                        this.getExcelData();
                        this.topRow = newTopRow;
                    }
                } else {
                    this.showInfo('没有更多数据');
                }
            }
        }
    }

    @action LeftColumnChanged = (e, info) => {
        // 左移右移时，隐藏
        this.filterVisible = false;
        // const { newLeftCol,oldLeftCol, sheet } = info;
        // // 右移
        // if(oldLeftCol > newLeftCol) {
        //     this.filterLeft = this.filterLeft + sheet.getColumnWidth(newLeftCol);
        // } else { // 左移
        //     this.filterLeft = this.filterLeft - sheet.getColumnWidth(oldLeftCol);
        // }
    }

    showInfo = (info) => {
        if (info === this.oldInfo) {
            window.clearTimeout(this.clearInfoTimer);
            this.clearInfoTimer = window.setTimeout(() => {
                this.oldInfo = '';
            }, 700);
        } else {
            message.info(info);
            this.oldInfo = info;
        }

    }

    @action showFilter = (filterKey, hitInfo, transMethodOther) => {
        const { cellRect } = hitInfo;
        const { top, left } = $(this.workbook.getHost()).offset();
        const { x, y, width, height } = cellRect;
        this.filterLeft = x + left;
        this.isShowAdSearch = true;
        if (transMethodOther && transMethodOther.split("+")[0] == '6') {
            this.isShowAdSearch = false;
        }
        if ((this.filterLeft + Math.max(400, width)) > this.clientWidth) {
            this.filterLeft = this.clientWidth - Math.max(400, width);
        }
        this.filterTop = y + top + height - 5;
        this.filterWidth = width;
        this.filterVisible = true;
        this.filterLoading = true;
        this.filterKey = filterKey;

        if (this.columnsSearch[filterKey] && this.columnsSearch[filterKey].value == 1) {
            this.isSearch = 1;
        } else {
            this.isSearch = 0;
        }

        const res = this.filterQueryedDatas[filterKey];
        if (res) {
            this.initFilter(hitInfo, filterKey, res);
        } else {

            API.filterDatas({
                ...this.designStore.params,
                formid: this.designStore.selectedForm,
                taskid: this.designStore.selectedTask,
                appid: this.designStore.appid,
                //quickSearchValue: this.designStore.quickSearchValue,
                filterKey: filterKey,
                //...this.designStore.conditionForm.getFormParams(),
                sortParams: this.sort

            }).then((res) => this.initFilter(hitInfo, filterKey, res));
        }
        this.designStore.showContent(false);

    }

    @action initFilter = (hitInfo, filterKey, res) => {

        this.filterLoading = false;
        this.filterOptions = res[filterKey];
        this.filterValue = this.filterCheckedValue[filterKey] || this.filterOptions.map(r => r.value);
        this.filterQueryedDatas[filterKey] = res;
        this.sortType = "";
        this.quickSearchValue = "";

        if (this.sortKey) {
            if (this.sortKey.split("@")[0] == filterKey) {
                this.sortType = this.sortKey.split("@")[1];
            }
        }
        this.valueCheck(this.filterValue);
        // setTimeout(() => {
        //     this.filterLoading = false;
        //     this.filterOptions = [1,2,3,4,5,6,7,8,9,0].map(d=>({value:d, label:`label${d}`}))
        // }, 1000);
    }

    @action hideFilter = () => {
        this.filterVisible = false;
    }

    @action changeSelectValue = (v) => {
        this.selectValue = v;

    }

    onFilter = () => {
        // 首先将选定值写入过滤map中
        this.filterCheckedValue[this.filterKey] = this.filterValue;
        // 然后在进行筛选

        // 加一个筛选：如果选择全部值，则不参加过滤条件
        let filterMap = {};
        for (var key in this.filterCheckedValue) {
            if (this.filterCheckedValue[key] && this.filterQueryedDatas[key] && this.filterCheckedValue[key].length != this.filterQueryedDatas[key][key].length) {
                filterMap[key] = this.filterCheckedValue[key];
            }
        }
        API.data({
            ...this.designStore.params,
            formid: this.designStore.selectedForm,
            taskid: this.designStore.selectedTask,
            ...this.designStore.conditionForm.getFormParams(),
            data: this.data,
            filterMap: JSON.stringify(filterMap)
        }).then(this.setData);
    }


    setData = (result) => {
        this.designStore.sessionKey = result.datas;
        this.sessionKey = result.datas;
        this.page = 1;
        this.getExcelData();
    }

    selectHide = () => {
        this.filterVisible = false;
    }

    @action onChange = (value) => {
        this.filterValue = value;

        this.valueCheck(value);

    }

    @action valueCheck = (value) => {
        if (!value || value.length == 0) {
            this.indeterminate = false;
            this.checkAll = false;
        } else if (!this.filterQueryedDatas || !this.filterQueryedDatas[this.filterKey] || !this.filterQueryedDatas[this.filterKey][this.filterKey]) {
            this.indeterminate = false;
            this.checkAll = false;
        } else if (value.length >= this.filterQueryedDatas[this.filterKey][this.filterKey].length) {
            this.indeterminate = false;
            this.checkAll = true;
        } else {
            this.indeterminate = true;
            this.checkAll = false;
        }
    }

    @action onCheckAllChange = e => {
        this.filterValue = e.target.checked ? this.filterQueryedDatas[this.filterKey][this.filterKey]
            .map(r => r.value) : [];
        this.indeterminate = false;
        this.checkAll = e.target.checked;

    };

    @action quickSearch = (value) => {
        this.quickSearchValue = value;
        this.filterOptions = this.quickSearchValue ? this.filterQueryedDatas[this.filterKey][this.filterKey]
            .filter(d => d.label.indexOf(this.quickSearchValue) > -1)
            : this.filterQueryedDatas[this.filterKey][this.filterKey];
    }

    @action refreshExcel = () => {
        setTimeout(() => {
            this.workbook.refresh();
        }, 100);
    }

    @action lockCol = () => {

        const col = this.workbook.getActiveSheet().getActiveColumnIndex();
        const { col: startCol } = this.table.dataRange();
        const colIndex = col - startCol + 1;
        if (colIndex == this.lockColumn) {
            this.lockColumn = "";
            this.colLock = 0;
            this.workbook.getActiveSheet().frozenColumnCount(0);
        } else {
            this.lockColumn = colIndex;
            this.colLock = 1;
            this.workbook.getActiveSheet().frozenColumnCount(colIndex);
        }

    }

    @action deleteData = () => {
        const _this = this;

        const selections = _this.workbook.getActiveSheet().getSelections();
        let rows = [];
        selections.forEach(selection => {
            let { row, col, rowCount, colCount } = selection;
            if (row == -1) {
                row = 0;
            }
            for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                rows.push(row + rowIndex);
            }
        });
        rows = uniqBy(rows);

        const datas = this.dataSource.getValue('datas');

        //const rowData = datas[dataIndex];

        let dataIds;
        if (this.designStore.fillinType === fillinTypes.MULTI) {
            //store.showExcel(operate.otherpara,record.randomFieldId);
            dataIds = rows.map(r => datas[r].randomFieldSubKeyid || datas[r].randomFieldId);
            //console.log(dataIds, _this.designStore.selectedForm, _this.designStore.appid);
            // this.designStore.slideStore.init(this.params = {
            //     pageid: this.otherpara, userdataid: rowData.randomFieldId
            // });
        } else {
            dataIds = rows.map(r => datas[r].randomFieldId);
            //console.log(dataIds, _this.designStore.selectedForm, _this.designStore.appid);
            //this.designStore.fetchDetailData(rowData.randomFieldId, this.otherpara);
        }

        if (dataIds && dataIds.length > 0)
            Modal.confirm({
                content: getLabel('4053', '是否确认删除？'),
                onOk() {
                    //const dataIds = _this.tableStore.selectedRowKeys.join(",");
                    let data = {};
                    //data = { formid: _this.selectedForm, dataIds: dataIds };
                    switch (_this.designStore.fillinType) {
                        case fillinTypes.MULTI:
                            data = { formid: _this.designStore.selectedForm, dataIds: dataIds };
                            break;
                        case fillinTypes.FREE:
                            data = { appid: _this.designStore.appid, dataIds: dataIds };
                            break;
                    }
                    API.delete(data).then(data => {
                        message.success(getLabel('5345', '删除成功！'));
                        _this.designStore.reloadData();
                    })
                },
            });

    }

    // 改变对齐方式
    changeHAlign = (align) => {
        // const _this = this;
        const old = JSON.stringify(this.columnsAlign)
        const selections = this.workbook.getActiveSheet().getSelections();
        let cols = [];
        const activeSheet = this.workbook.getActiveSheet();
        selections.forEach(selection => {
            let { row, col, rowCount, colCount } = selection;
            if (col == -1) {
                col = 0;
            }
            for (let colIndex = 0; colIndex < colCount; colIndex++) {
                cols.push(col + colIndex);
            }
        });
        cols = uniqBy(cols);
        this.colAlign = align;
        cols.forEach(col => {
            if (this.columnList[col]) {
                this.columnsAlign[this.columnList[col]] = align;
            }
            activeSheet.getRange(-1, col).hAlign(align);
        })
        if (JSON.stringify(this.columnsAlign) != old) {
            this.saveExcelStyle({ columnsAlign: JSON.stringify(this.columnsAlign) });
        }
    }

    // 宽度变化
    columnWidthChanged = (e, info) => {
        const { colList, sheet } = info;
        colList.forEach(d => {
            if (this.columnList[d]) {
                this.columnsWith[this.columnList[d]] = sheet.getColumnWidth(d);
            }
        });
        this.filterVisible = false;
        this.saveExcelStyle({ columnsWith: JSON.stringify(this.columnsWith) });
    }

    // 保存Excel格式
    saveExcelStyle = (params) => {
        API.saveExcelStyle({
            formid: this.designStore.selectedForm,
            appid: this.designStore.appid,
            ...params,
            columnsSearch: JSON.stringify(this.columnsSearch),
        }).then(this.designStore.updateConditions);

    }

    // 搜索改变
    changeSearch = (value) => {
        let searchCol = this.colPropList[this.filterKey];
        if (searchCol) {
            //htmltype 1: inttype 10 评分；2：文本；3：浏览框；4：是否；5：下拉框；6：图片（不过滤）
            // intType:2,19,290 日期 ，浏览框类型
            searchCol.value = value;
            const transMethodOther = searchCol.transMethodOther;
            const transMethod = searchCol.transMethod;
            const title = searchCol.title;
            // 判断是否是地址字段
            if (transMethod && transMethod.indexOf('getComplexShowText') > -1) {
                this.columnsSearch[this.filterKey] = { value, transMethodOther, title };
            } else {

                this.columnsSearch[this.filterKey] = { value, transMethodOther };
            }
            this.saveExcelStyle({ columnsSearch: JSON.stringify(this.columnsSearch) });
            //this.designStore.updateConditions(searchCol);
            this.isSearch = value;
        }

        //this.filterVisible = false;
    }

    saveDownloadCondition = () => {
        this.downloadCondition.isdownload = this.isdownload;
        this.downloadCondition.fieldgroup = this.fieldgroup;
        this.saveExcelStyle({ downloadCondition: JSON.stringify(this.downloadCondition) });

        this.designStore.showContent(false);

    }

    reloadData = () => {
        this.page = 1;
        this.getExcelData();
    }

    updateIsDownloadField = (value) => {
        this.isdownload = value;

    }
    updateDownloadCondition = (value) => {
        this.fieldgroup = value;

    }
}